package zkk.com.mengqu.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jakewharton.rxbinding.view.RxView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.bingoogolapple.bgabanner.BGABanner;
import cn.bingoogolapple.bgabanner.BGABannerUtil;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import zkk.com.mengqu.R;
import zkk.com.mengqu.adapter.NearByKitchenAdapter;
import zkk.com.mengqu.manager.APIManager;
import zkk.com.mengqu.models.Banner;
import zkk.com.mengqu.models.KitchenDetail;
import zkk.com.mengqu.models.KitchenList;
import zkk.com.mengqu.models.SpinnerItem;
import zkk.com.mengqu.simplepreferences.Share;
import zkk.com.mengqu.view.refresh.LoadMoreListView;

/**
 * 首页厨房列表
 */
public class NearByKitchenFragment extends Fragment implements BGABanner.Delegate<ImageView, String> {
    private View view;
    private Context context;
    private LoadMoreListView listView;
    private NearByKitchenAdapter adapter;
    private SwipeRefreshLayout refresh;//下拉刷新
    private List<KitchenDetail> lists = new ArrayList<>();
    private BGABanner banner;

    //悬浮部分
    private LinearLayout invis;

    //spinner
    private  Spinner mMainSp1,mMainSp2,mMainSp3,mItemSp1,mItemSp2,mItemSp3;
    private List<SpinnerItem> data_list1;
    private List<SpinnerItem> data_list2;
    private List<SpinnerItem> data_list3;
    private int position1 = 0;//第一个spinner选择的
    private int position2 = 0;//第二个spinner选择的
    private int position3 = 0;//第三个spinner选择的
    private int value1 = 0;
    private int value2 = 0;
    private int value3 = 0;
    private BaseAdapter arr_adapter;//适配器

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_kitchen_all,null);
        context = getActivity();
        initView();
        //设置banner
        setBanner();
        //
        setSpinner();

        getBanners();
        return view;
    }

    public void initView(){
        invis = (LinearLayout) view.findViewById(R.id.invis);
        listView = (LoadMoreListView) view.findViewById(R.id.expandableListView);//listView
        refresh = (SwipeRefreshLayout)view.findViewById(R.id.shelf_swipe_refresh);//下拉刷新
        refresh.setColorSchemeColors(Color.GREEN, Color.RED, Color.YELLOW);//下拉刷新颜色
//        shelf_swipe_refresh.setEnabled(true);
        adapter = new NearByKitchenAdapter(context,lists);
        listView.setAdapter(adapter);

        //下拉刷新最后一项
        listView.setOnLastItemVisibleListener(new LoadMoreListView.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                Log.w("LastItem","LastItem");
            }
        });

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//                Intent intent = new Intent(AD_DOWNLOAD_ACTION);


                boolean enable = false;
                if(listView != null && listView.getChildCount() > 0){
                    // check if the first item of the list is visible
                    boolean firstItemVisible = listView.getFirstVisiblePosition() == 0;
                    // check if the top of the first item is visible
                    boolean topOfFirstItemVisible = listView.getChildAt(0).getTop() == 0;
                    // enabling or disabling the refresh layout
                    enable = firstItemVisible && topOfFirstItemVisible;
                }
                refresh.setEnabled(enable);
                if (!enable){
                    if (firstVisibleItem >= 1){
                        invis.setVisibility(View.VISIBLE);
//                    intent.putExtra("resource", "111");
                    }else {
                        invis.setVisibility(View.GONE);
//                    intent.putExtra("resource", "222");
                    }
                }

//                LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
            }
        });

        //下拉刷新
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh.setRefreshing(true);
                getBanners();
            }
        });
    }

    //设置banner
    public void setBanner(){
        View headView = LayoutInflater.from(getActivity()).inflate(R.layout.item_banner , null);//banner
        listView.addHeaderView(headView);
        banner = (BGABanner) headView.findViewById(R.id.banner);//
        getBanners();
    }

    //banner点击监听
    @Override
    public void onBannerItemClick(BGABanner banner, ImageView itemView, String model, int position) {
        Toast.makeText(getActivity(), "点击了第" + (position + 1) + "页", Toast.LENGTH_SHORT).show();
    }

    //初始化spinner
    public void setSpinner(){
        View spinner = LayoutInflater.from(getActivity()).inflate(R.layout.item_spinner , null);//ListView条目中的悬浮部分 添加到头部
        listView.addHeaderView(spinner);
        mMainSp1 = (Spinner)spinner.findViewById(R.id.item_sp1);
        mMainSp2 = (Spinner)spinner.findViewById(R.id.item_sp2);
        mMainSp3 = (Spinner)spinner.findViewById(R.id.item_sp3);

        mItemSp1 = (Spinner)view.findViewById(R.id.main_sp1);
        mItemSp2 = (Spinner)view.findViewById(R.id.main_sp2);
        mItemSp3 = (Spinner)view.findViewById(R.id.main_sp3);

        initSpinnerData();
        initSpinnerAdapter();
        setSpinnerListener();
    }

    //spinner的监听
    private void setSpinnerListener() {
        mMainSp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(getActivity(), "点击了"+data_list1.get(position), Toast.LENGTH_SHORT).show();
                position1 = position;
                mItemSp1.setSelection(position1);
                value1 = data_list1.get(position).getValue();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mMainSp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(getActivity(), "点击了"+data_list2.get(position), Toast.LENGTH_SHORT).show();
                position2 = position;
                mItemSp2.setSelection(position2);
                value2 = data_list2.get(position).getValue();
                getNearByKitchen(value2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mMainSp3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(getActivity(), "点击了"+data_list3.get(position), Toast.LENGTH_SHORT).show();
                position3 = position;
                mItemSp3.setSelection(position3);
                value3 = data_list3.get(position).getValue();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mItemSp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(getActivity(), "点击了"+data_list1.get(position), Toast.LENGTH_SHORT).show();
                position1 = position;
                mMainSp1.setSelection(position1);
                value1 = data_list1.get(position).getValue();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mItemSp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(getActivity(), "点击了"+data_list2.get(position), Toast.LENGTH_SHORT).show();
                position2 = position;
                mMainSp2.setSelection(position2);
                value2 = data_list2.get(position).getValue();
                getNearByKitchen(value2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mItemSp3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(getActivity(), "点击了"+data_list3.get(position), Toast.LENGTH_SHORT).show();
                position3 = position;
                mMainSp3.setSelection(position3);
                value3 = data_list3.get(position).getValue();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //设置spinner的设配器
    private void initSpinnerAdapter() {
        //适配器
        arr_adapter = new MyAdapter(data_list1);
        mMainSp1.setAdapter(arr_adapter);

        //适配器
        arr_adapter = new MyAdapter(data_list2);
        mMainSp2.setAdapter(arr_adapter);

        //适配器
        arr_adapter = new MyAdapter(data_list3);
        mMainSp3.setAdapter(arr_adapter);

        //适配器
        arr_adapter = new MyAdapter(data_list1);
        mItemSp1.setAdapter(arr_adapter);

        //适配器
        arr_adapter = new MyAdapter(data_list2);
        mItemSp2.setAdapter(arr_adapter);

        //适配器
        arr_adapter = new MyAdapter(data_list3);
        mItemSp3.setAdapter(arr_adapter);
    }

    //设置数据来源，这个要在网络获取。由于数据不会太多，不再考虑性能优化问题
    private void initSpinnerData() {
        //数据
        data_list1 = new ArrayList<>();
        data_list1.add(new SpinnerItem("价格", -1));
        data_list1.add(new SpinnerItem("20元以下", 0));
        data_list1.add(new SpinnerItem("40元以下", 1));
        data_list1.add(new SpinnerItem("60元以下", 2));
        data_list1.add(new SpinnerItem("80元以下", 3));
        data_list1.add(new SpinnerItem("100元以下", 4));

        //数据
        data_list2 = new ArrayList<>();
        data_list2.add(new SpinnerItem("距离最近", -1));
        data_list2.add(new SpinnerItem("2km以内", 2));
        data_list2.add(new SpinnerItem("4km以内", 4));
        data_list2.add(new SpinnerItem("6km以内", 6));
        data_list2.add(new SpinnerItem("8km以内", 8));

        //数据
        data_list3 = new ArrayList<>();
        data_list3.add(new SpinnerItem("人气", -1));
        data_list3.add(new SpinnerItem("从高到低", 0));
        data_list3.add(new SpinnerItem("从低到高", 1));
    }

    //接口-获取附近厨房
    private void getNearByKitchen(Integer distance){
        APIManager.setManager()
//                .getNearByKitchen("nearby_kitchen",113.584945,22.28563,"10KM")
                    .getNearByKitchen1(113.584945,22.28563,distance)
//                .getNearByKitchen1(Double.parseDouble(Share.getLatitude()),Double.parseDouble(Share.getLongitude()),1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<KitchenList>() {
                    @Override
                    public void onCompleted() {
                        Log.w("onCompleted","onCompleted");
                        refresh.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.w("onError","onError");
                        e.printStackTrace();
                        refresh.setRefreshing(false);
                    }

                    @Override
                    public void onNext(KitchenList kitchenList) {
                        if (kitchenList.getKitchens().size() != 0){
                            lists.clear();
                            Log.w("onNext","" + kitchenList.getKitchens().get(0));
                            lists.addAll(kitchenList.getKitchens());
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    /**
     * 获取广告轮播图
     *
     */
    public void getBanners(){
        APIManager.setManager()
                .getBanners()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<List<Banner>, Observable<KitchenList>>() {
                    @Override
                    public Observable<KitchenList> call(List<Banner> banners) {
                        List<String> paths = new ArrayList<String>();
                        List<String> tips = new ArrayList<String>();
                        for (Banner banner : banners){
                            paths.add(banner.getPath());
                            tips.add("");
                        }

                        banner.setData(paths, tips);
                        banner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
                            @Override
                            public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                                Glide.with(NearByKitchenFragment.this)
                                        .load(model)
                                        .placeholder(R.drawable.ic_user_icon_default)
                                        .error(R.drawable.ic_user_icon_default)
                                        .dontAnimate()
                                        .into(itemView);
                            }
                        });
                        banner.setDelegate(NearByKitchenFragment.this);//设置点击监听
                        return APIManager.setManager()
                                .getNearByKitchen1(113.584945,22.28563,5)//初始化默认5km范围内
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread());
                    }
                })
                .subscribe(new Observer<KitchenList>() {
                    @Override
                    public void onCompleted() {
                        Log.w("onCompleted","onCompleted");
                        refresh.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.w("onError","onError");
                        e.printStackTrace();
                        refresh.setRefreshing(false);
                    }

                    @Override
                    public void onNext(KitchenList kitchenList) {
                        if (kitchenList.getKitchens().size() != 0){
                            lists.clear();
                            Log.w("onNext","" + kitchenList.getKitchens().get(0));
                            lists.addAll(kitchenList.getKitchens());
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    //适配器
    class MyAdapter extends BaseAdapter {
        private LayoutInflater mLayoutInflater;
        private List<SpinnerItem> mDataList;

        MyAdapter(List<SpinnerItem> dataList) {
            this.mDataList = dataList;
            mLayoutInflater = LayoutInflater.from(getActivity());
        }

        @Override
        public int getCount() {
            return mDataList.size();
        }

        @Override
        public Object getItem(int position) {
            return mDataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        //数据不太多，没有使用ViewHolder进行处理。
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = View.inflate(getActivity(), R.layout.item_spinner_item, null);
            TextView textView = (TextView) convertView.findViewById(R.id.item_main_tv);
            textView.setText(mDataList.get(position).getKey());
            return convertView;
        }
    }

}